<template>
  <zh-form
      :span="6"
      ref="rolePageFrom"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :model="formData"
      :rules="rules"
  >
    <div style="padding: 15px 20px">
      <zh-row>
        <zh-input
            prop="b0128"
            :disabled="editFlag"
            type="text"
            label="序号"
            v-model="formData.b0128"
        ></zh-input>
        <zh-input
            prop="b0103"
            :disabled="editFlag"
            type="text"
            label="文物编号"
            v-model="formData.b0103"
        ></zh-input>
        <zh-input
            prop="b0102"
            :disabled="editFlag"
            type="text"
            label="文物名称"
            v-model="formData.b0102"
        ></zh-input>
        <zh-input
            prop="b0122"
            :disabled="editFlag"
            type="select"
            :options="sqData"
            :defaultFields="{ label: 'orgName', value: 'orgId' }"
            label="县市区"
            v-model="formData.b0122"
            @change="handleChangeB0122"
        ></zh-input>
        <zh-input
            prop="b0123"
            :disabled="editFlag"
            type="select"
            :options="jdDataArray"
            :defaultFields="{ label: 'orgName', value: 'orgId' }"
            label="乡镇街道"
            v-model="formData.b0123"
            @change="handleChangeB0123"
        ></zh-input>
        <zh-input
            prop="b0117"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0117"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="文保类别"
            v-model="formData.b0117"
        ></zh-input>
        <zh-input
            prop="b0118"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0118"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="文保子类"
            v-model="formData.b0118"
        ></zh-input>
        <zh-input
            prop="b0104"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0104"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="古系列类别"
            v-model="formData.b0104"
        ></zh-input>
        <zh-input
            prop="b0105"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0105"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="文保级别"
            v-model="formData.b0105"
        ></zh-input>
        <zh-input
            prop="b0106"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0106"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="时代"
            v-model="formData.b0106"
        ></zh-input>
<!--        <zh-input-->
<!--            prop="b0121"-->
<!--            :disabled="editFlag"-->
<!--            type="date"-->
<!--            format="YYYY-MM-DD HH:mm:ss"-->
<!--            v-model="formData.b0121"-->
<!--            :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"-->
<!--            label="开放时间"-->
<!--        />-->
        <zh-input
            prop="b0121"
            :disabled="editFlag"
            type="text"
            label="开放时间"
            v-model="formData.b0121"
        ></zh-input>
        <zh-input
            prop="b0114"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0114"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="是否安全"
            v-model="formData.b0114"
        ></zh-input>
        <zh-input
            prop="b0113"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0113"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="是否核销"
            v-model="formData.b0113"
        ></zh-input>
        <zh-input
            prop="b0115"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0115"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="划定保护双线"
            v-model="formData.b0115"
            :labelCol="{span:10}" :wrapperCol="{span:14}"
        ></zh-input>
        <zh-input
            prop="b0134"
            :disabled="editFlag"
            type="text"
            label="文物保护范围"
            v-model="formData.b0134"
        ></zh-input>
        <zh-input
            prop="b0135"
            :disabled="editFlag"
            type="text"
            label="建设控制地带范围"
            :labelCol="{span:10}" :wrapperCol="{span:14}"
            v-model="formData.b0135"
        ></zh-input>
        <zh-input
            prop="b0129"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0129"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="巡查级别"
            v-model="formData.b0129"
            :labelCol="{span:10}" :wrapperCol="{span:14}"
        ></zh-input>
        <zh-input
            prop="b0132"
            :disabled="editFlag"
            type="tree"
            :tree-data="treeData"
            :tree-checkable="true"
            label="是否开启详情"
            v-model="formData.b0132"
            :labelCol="{span:10}" :wrapperCol="{span:14}"
            @change="onChangeSelectTree"
        ></zh-input>
        <zh-input
            prop="b0130"
            :disabled="editFlag"
            type="text"
            label="批次"
            v-model="formData.b0130"
        ></zh-input>
        <zh-input
            prop="b0131"
            :disabled="editFlag"
            type="text"
            label="检查要点"
            v-model="formData.b0131"
        ></zh-input>
        <zh-input
            prop="b0136"
            :disabled="editFlag"
            type="text"
            placeholder="多个标签用,分开"
            label="标签"
            v-model="formData.b0136"
        ></zh-input>
        <zh-input
            prop="b0137"
            :disabled="editFlag"
            type="number"
            label="打卡范围(米)"
            v-model="formData.b0137"
        ></zh-input>
        <zh-input
            prop="b0133"
            :disabled="editFlag"
            type="select"
            :options="dictData.B0133"
            :defaultFields="{ label: 'dictValue', value: 'dictKey' }"
            label="是否申报点"
            v-model="formData.b0133"
        >
        </zh-input>
        <p class="title">(用于统计)</p>
      </zh-row>
      <zh-row>
        <zh-input
            prop="b0116"
            :disabled="editFlag"
            type="textarea"
            label="基本简介"
            v-model="formData.b0116"
            style="float: left"
            :labelCol="{ span: 2 }"
            :wrapperCol="{ span: 22 }"
            :span="24"
            :rows="3"
        ></zh-input>
      </zh-row>
      <zh-row>
        <zh-input
            prop="b0125"
            :disabled="true"
            type="text"
            label="留档地址"
            :span="11"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 19 }"
            v-model="formData.b0125"
        ></zh-input>
        <zh-input
            style="margin-left: 62px"
            prop="b0126"
            :disabled="true"
            type="text"
            label="原经度"
            :span="4"
            v-model="formData.b0126"
        ></zh-input>
        <zh-input
            prop="b0127"
            :disabled="true"
            type="text"
            label="原纬度"
            :span="4"
            v-model="formData.b0127"
        ></zh-input>
      </zh-row>
      <zh-row>
        <zh-input
            prop="b0109"
            :disabled="editFlag"
            type="text"
            label="地址"
            :span="11"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 19 }"
            v-model="formData.b0109"
        ></zh-input>
        <ep-button
            style="margin-top: 4px"
            type="primary"
            size="small"
            @click="queryTude()"
        >重新定位
        </ep-button
        >
        <zh-input
            prop="b0111"
            :disabled="editFlag"
            type="text"
            label="经度"
            :span="4"
            v-model="formData.b0111"
            @blur="pickUp"
        ></zh-input>
        <zh-input
            prop="b0112"
            :disabled="editFlag"
            type="text"
            label="纬度"
            :span="4"
            v-model="formData.b0112"
            @blur="pickUp"
        ></zh-input>
<!--        <ep-button-->
<!--                  style="margin-top: 4px; margin-left: 15px"-->
<!--                  type="primary"-->
<!--                  size="small"-->
<!--                  @click="pickUp"-->
<!--                  >拾取</ep-button-->
<!--                >-->
      </zh-row>
      <div class="map-box">
        <div id="gssp"></div>
        <div class="scale">
          <p @click="checkEnlarge">
            <span>+</span>
          </p>
          <p @click="checkNarrow">
            <span>-</span>
          </p>
        </div>
      </div>
    </div>
  </zh-form>
</template>

<script>
import {getBatchDict, getDictCondition} from "@/services/system/api";
import {getSQAndJD} from "@/services/system/whdngxlApi";
import {interfaceExtraDic} from "@/services/system/apiLog";
import AMapLoader from "@amap/amap-jsapi-loader";
import {gcj02towgs84} from "@/utils/wgs84.js";
import moment from 'moment';
const treeData = [
  {
    title: '否',
    value: '0',
    key: '0',
  },
  {
    title: '是',
    value: '11',
    key: '11',
    disabled: true,
    children: [
      {
        title: '气象检测',
        value: '1',
        key: '1',
      },
      {
        title: '水位检测',
        value: '2',
        key: '2',
      },
      {
        title: '振动检测',
        value: '3',
        key: '3',
      },
    ],
  },
];

export default {
  props: {
    c0303: {
      required: false
    },
    classify: {
      required: false
    },
    flag: {
      required: false,
      type: String,
      default: () => {
        return undefined;
      },
    },
  },
  data() {
    return {
      treeData,
      dictData: {},
      editFlag: true,
      formData: {
        b0128: "",
        b0102: "",
        b0103: "",
        b0107: "",
        b0108: "",
        b0117: "",
        b0118: "",
        b0104: "",
        b0105: "",
        b0106: "",
        b0115: "",
        b0114: "",
        b0125: "",
        b0126: "",// 国家2000坐标
        b0127: "",
        gpsLongitude_b0126: "", // 高德地图坐标
        gpsLatitude_b0127: "",
        b0113: "",
        b0116: "",
        b0109: "",
        b0111: "", // 国家2000坐标
        b0112: "",
        gpsLongitude: "", // 高德地图坐标
        gpsLatitude: "",
        b0122: "",
        b0123: "",
        b0129: "",
        b0130: "",
        b0131: "",
        b0132: "",
        b0133: "",
        b0134: "",
        b0135: "",
        b0136: "",
        b0137: "",
      },
      zoomSize: 12,
      massMarks: "",
      areaMap: null,
      areaForm: {
        range: [],
        control: [],
      },
      rangePolygon: null,
      controlPolygon: null,
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      rules: {},
      sqData: [],
      jdData: {},
      jdDataArray: [],
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    // 销毁地图
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    initTreeData(data){
      if(data.indexOf("0") > -1){
        this.treeData[0].disabled=false
        this.treeData[1].disabled=true
        this.treeData[1].children.forEach(item =>{
          item.disabled = true
        })
      }else if(data.indexOf("1") > -1 || data.indexOf("2") > -1 ||data.indexOf("3") > -1){
        this.treeData[0].disabled=true
        this.treeData[1].disabled=true
        this.treeData[1].children.forEach(item =>{
          item.disabled = false
        })
      }else {
        this.treeData[0].disabled=false
        this.treeData[1].disabled=true
        this.treeData[1].children.forEach(item =>{
          item.disabled = false
        })
      }
    },
    onChangeSelectTree(){
      console.log(...arguments)
      this.initTreeData(arguments[0])
    },
    moment,
    handleChangeB0122(orgId, option) {
      this.jdDataArray = this.jdData[orgId];
      for (const item of option) {
        if (item.orgId === orgId) {
          this.formData.b0107 = item.orgName;
          break;
        }
      }
    },
    handleChangeB0123(orgId, option) {
      for (const item of option) {
        if (item.orgId === orgId) {
          this.formData.b0108 = item.orgName;
          break;
        }
      }
    },
    init() {
      const params = {};
      params.dictFields = "B0106,B0113,B0114,B0115,B0117,B0118,B0129,B0133";
      this.$http.post(getBatchDict, params).then((res) => {
        let resultData = JSON.parse(JSON.stringify(this.dictData));
        resultData.B0104 = res.result.B0104;
        resultData.B0106 = res.result.B0106;
        resultData.B0113 = [
          {dictKey: "0", dictValue: "否"},
          {dictKey: "1", dictValue: "是"},
        ];
        resultData.B0114 = [
          {dictKey: "0", dictValue: "否"},
          {dictKey: "1", dictValue: "是"},
        ];
        resultData.B0115 = [
          {dictKey: "0", dictValue: "否"},
          {dictKey: "1", dictValue: "是"},
        ];
        resultData.B0133=res.result.B0133;
        console.log(this.formData.b0133)
        resultData.B0117 = res.result.B0117;
        resultData.B0118 = res.result.B0118;
        resultData.B0129 = res.result.B0129;
        this.dictData = resultData;
      });

      this.$http.post(getDictCondition, {dictField: 'B0105',classify: this.classify}).then(res => {
        this.$set(this.dictData, 'B0105', res.result)
      })
      this.$http.post(getDictCondition, {dictField: 'B0104',classify: this.classify}).then(res => {
              this.$set(this.dictData, 'B0104', res.result)
            })

      this.$http.post(getSQAndJD, {}).then((res) => {
        this.sqData = res.result.sqData;
        this.jdData = res.result.jdData;

        if (this.formData && this.formData.b0122) {
          this.jdDataArray = this.jdData[this.formData.b0122];
        }
      });

      if(this.flag === 'save'){
        setTimeout(()=>{
          this.formData.b0115 = '0'
          this.formData.b0132 = '0'
        },500)
      }
    },
    initMap() {
      AMapLoader.load({
        key: "e38ea4dfc12f0fd7864f078c6ce7b48d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Marker",
          "AMap.Pixel",
          "AMap.DistrictSearch",
          "AMap.Autocomplete", // 输入提示插件
          "AMap.PlaceSearch", // POI搜索插件
          "AMap.Scale", // 右下角缩略图插件 比例尺
          "AMap.OverView", // 地图鹰眼插件
          "AMap.ToolBar", // 地图工具条
          "AMap.MapType", // 类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          "AMap.PolyEditor", // 编辑 折线多，边形
          "AMap.CircleEditor", // 圆形编辑器插件
          "AMap.Geolocation", // 定位控件，用来获取和展示用户主机所在的经纬度位置
          "AMap.Geocoder",
        ],
      })
          .then((AMap) => {
            window.AMap = AMap;
            if (this.formData.b0111 && this.formData.b0112) {
              this.convertGps(this.formData.b0111, this.formData.b0112).then(() => {
                this.renderMap(true);
              });
            } else {
              this.renderMap(false);
            }
          })
          .catch((e) => {
            console.log(e);
          });
    },
    // WGS84坐标系(精度小于10米同国家2000坐标系) 转换成高德坐标系
    convertGps(longitude, dimension, type) {
      return new Promise((resolve, reject) => {
        AMap.convertFrom(
            [longitude, dimension],
            "gps",
            (status, result) => {
              if (status == "complete") {
                let lnglats = result.locations[0];
                if (type === 'b0125') {
                  this.$set(this.formData, "gpsLongitude_b0126", lnglats.lng);
                  this.$set(this.formData, "gpsLatitude_b0127", lnglats.lat);
                } else {
                  this.$set(this.formData, "gpsLongitude", lnglats.lng);
                  this.$set(this.formData, "gpsLatitude", lnglats.lat);
                }
                resolve();
              } else {
                reject();
                this.$message.error("坐标转换失败，请联系管理员！");
              }
            }
        );
      });
    },
    // 高德坐标系 转换成 WGS84坐标系(精度小于10米同国家2000坐标系)
    convertGcj() {
      let wgsArr = gcj02towgs84(
          this.formData.gpsLongitude,
          this.formData.gpsLatitude
      );
      this.$set(this.formData, "b0111", wgsArr[0]);
      this.$set(this.formData, "b0112", wgsArr[1]);
    },

    // 渲染地图
    renderMap(flag) {
      this.map = new AMap.Map("gssp", {
        resizeEnable: true,
        zoom: this.zoomSize, //初始化地图级别
        center: [
          this.formData.gpsLongitude || 120.699279,
          this.formData.gpsLatitude || 27.993849,
        ], //初始化地图中心点位置
      });
      this.map.setDefaultCursor("pointer");
      this.map.on("click", (e) => {
        this.formData.gpsLongitude = e.lnglat.getLng();
        this.formData.gpsLatitude = e.lnglat.getLat();
        this.convertGcj();
        this.pickUp();
      });
      if (flag) {
        if (this.formData.b0109) {
          this.setPoint();
        } else {
          this.pickUp();
        }
      } else {
        // 没有经纬度，但是有地址的时候
        if (this.formData.b0109) {
          this.queryTude();
        }
      }
      var text = new AMap.Text({ //添加文字点标记
        map: this.map,
        // position: [120.6313, 28.0208], //基点位置
        draggable: false, //是否可拖动
        offset:[900,0],//偏移量
        content: '<div style="border:1px solid #ccc;background:#fff;white-space:nowrap; padding:3px;font-size:14px;">请在地图上选择点位落点</div>' //自定义点标记覆盖物内容
      });

      this.map.add(text)
    },

    // 地址-查询
    queryTude() {
      if (!this.formData.b0109) {
        this.$message.error("请输入详细地址");
        return;
      }
      const autoOptions = {
        city: "0577", // 兴趣点城市
        citylimit: true, //是否强制限制在设置的城市内搜索
      };
      const geoLngLat = new AMap.Geocoder(autoOptions);
      geoLngLat.getLocation(this.formData.b0109, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          let lnglat = result.geocodes[0].location || {};
          this.$set(this.formData, "gpsLongitude", lnglat.lng);
          this.$set(this.formData, "gpsLatitude", lnglat.lat);
          this.convertGcj();
          this.setPoint();
        } else {
          this.$message.error("根据地址查询位置失败");
        }
      });
    },
    // 经纬度-拾取
    pickUp() {
      if (!this.formData.b0111) {
        if(this.formData.b0101){//新增时经度为空不提示
          this.$message.error("请输入经度");
        }
        return;
      }
      if (!this.formData.b0112) {
        if(this.formData.b0101) {//新增时纬度为空不提示
          this.$message.error("请输入纬度");
        }
        return;
      }

      this.convertGps(this.formData.b0111, this.formData.b0112).then(() => {
        const geoOptions = {
          city: "0577", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          radius: 1000,
        };
        const geocoder = new AMap.Geocoder(geoOptions);
        geocoder.getAddress(
            [this.formData.gpsLongitude, this.formData.gpsLatitude],
            (status, result) => {
              if (status === "complete" && result.regeocode) {
                let b0109 = result.regeocode.formattedAddress;
                this.$set(this.formData, "b0109", b0109);
                this.setPoint();
              } else {
                this.$message.error("根据经纬度查询地址失败");
              }
            }
        );
      });
    },
    // 原经纬度-拾取
    pickUpB0125() {
      if (!this.formData.b0126) {//原经度
        return;
      }
      if (!this.formData.b0127) {//原纬度
        return;
      }
      this.convertGps(this.formData.b0126, this.formData.b0127, 'b0125').then(() => {
        const geoOptions = {
          city: "0577", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          radius: 1000,
        };
        const geocoder = new AMap.Geocoder(geoOptions);
        geocoder.getAddress(
            [this.formData.gpsLongitude_b0126, this.formData.gpsLatitude_b0127],
            (status, result) => {
              if (status === "complete" && result.regeocode) {
                let b0125 = result.regeocode.formattedAddress;
                this.$set(this.formData, "b0125", b0125);
                this.setPoint();
              } else {
                this.$message.error("根据原经纬度查询留档地址失败");
              }
            }
        );
      });
    },

    // 安放点位
    setPoint() {
      if (this.massMarks) {
        this.massMarks.setData([]);
        // this.massMarks.setMap(null);
        // this.massMarks.clear()
      }
      var styleObject = [{
        //url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
        url: require("@/assets/img/icon-pointLiu.png"),  // 图标地址
        //anchor: new AMap.Pixel(50, 50),
        anchor:'bottom-center', // 设置锚点方位

        size: new AMap.Size(100, 100),
        // zIndex: 每种样式图标的叠加顺序，数字越大越靠前
        zIndex: 99,
      }, {
        url: require("@/assets/img/icon-point.png"),  // 图标地址
        size: new AMap.Size(60, 60),      // 图标大小
        // anchor: new AMap.Pixel(-20, -20),// 图标显示位置偏移量，基准点为图标左上角
        anchor:'bottom-center', // 设置锚点方位
        zIndex: 10,
      }]
      this.massMarks = new AMap.MassMarks(null, {
        zIndex: 2,  // 海量点图层叠加的顺序
        zooms: [0, 30],  // 在指定地图缩放级别范围内展示海量点图层
        style: styleObject  // 设置样式对象
      });
      var data = []
      if (this.formData.gpsLongitude_b0126 === undefined || this.formData.gpsLatitude_b0127 === undefined) {
        this.pickUpB0125();

      }
      if (this.formData.gpsLongitude === undefined
          || this.formData.gpsLatitude === undefined) {
        data = []
      } else if (this.formData.gpsLongitude_b0126 === undefined
          || this.formData.gpsLatitude_b0127 === undefined) {
        data = [{
          lnglat: [this.formData.gpsLongitude, this.formData.gpsLatitude], //点标记位置
          name: 'b0109',
          style: 1, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 1
        },];
      } else {
        data = [{
          lnglat: [this.formData.gpsLongitude, this.formData.gpsLatitude], //点标记位置
          name: 'b0109',
          style: 1, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 1
        }, {
          lnglat: [this.formData.gpsLongitude_b0126, this.formData.gpsLatitude_b0127], //点标记位置
          name: 'b0125',
          style: 0, // 该数据的样式取值styleObjectArr对应的样式索引
          id: 2
        },
        ];
      }


      this.massMarks.setData(data);
      // 将海量点添加至地图实例
      this.massMarks.setMap(this.map);
      this.zoomSize = 15;
      this.map.setZoom(this.zoomSize);
      this.map.setCenter(
          [this.formData.gpsLongitude, this.formData.gpsLatitude,]
      );
    },
    // 地图-放大
    checkEnlarge() {
      this.map.setZoom((this.zoomSize += 1));
    },
    // 地图-缩小
    checkNarrow() {
      if (this.zoomSize > 8) {
        this.map.setZoom((this.zoomSize -= 1));
      }
    },
  },
  watch: {
    'formData.b0132': {
      handler(newValue) {
        console.log(newValue)
        if(typeof this.formData.b0132 === "string"){
          this.formData.b0132 = this.formData.b0132.split(",")
          this.initTreeData(this.formData.b0132)
        }
      },
      immediate: true,
      deep: true
    },
  }
};
</script>

<style lang="less" scoped>
.map-box {
  position: relative;
  height: 600px;
  padding-left: 20px;

  #gssp {
    height: 100%;
  }

  #area {
    height: 100%;
  }

  .scale {
    position: absolute;
    top: 20px;
    left: 40px;
    width: 30px;
    height: 80px;
    display: flex;
    flex-direction: column;

    p {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #dfdfdf;
      background: #fff;
      font-size: 22px;
      color: #49bbeb;
      cursor: pointer;

      &:first-child {
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
      }

      &:last-child {
        border-top: none;
        border-bottom-left-radius: 3px;
        border-bottom-right-radius: 3px;
      }

      &:hover {
        background: #f2f2f2;
      }
    }
  }
}
</style>
<style>
.amap-logo,
.amap-copyright {
  display: none !important;
}
</style>
